package com.muqi.app.qlearn.student.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.NumberFormatUtil;
import com.muqi.app.qlearn.adapter.ClassRoomCommentStatisticsAdapter;
import com.muqi.app.qlearn.fragments.BannerFragment;
import com.muqi.app.qlearn.modles.ClassRoomCommentStatisticsEntity;
import com.muqi.app.qlearn.modles.StatisticsInfo;
import com.muqi.app.qlearn.modles.StatisticsListInfo;
import com.muqi.app.qlearn.student.BaseStudentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.widget.ClubWindow;
import com.muqi.app.user.widget.ClubWindow.ClickClubWindowListener;
import com.muqi.app.widget.pulltorefresh.XListView;

public class ClassRoomCommentStatisticsActivity extends BaseStudentActivity
		implements OnClickListener, ClickClubWindowListener,
		XListView.IXListViewListener {
	private PieChart mPieChart;
	private List<ClassRoomCommentStatisticsEntity> statisticsList = new ArrayList<ClassRoomCommentStatisticsEntity>();
	private XListView mList;
	private TextView tv_title;
	private ClubWindow mywindow = null;
	private String timeType = "all";
	private int page = 1;
	private ArrayList<StatisticsListInfo> listInfos = new ArrayList<StatisticsListInfo>();
	private ClassRoomCommentStatisticsAdapter adapter;
	private String selectChildId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_classromm_comment_statistics);
	}

	@Override
	protected void onInit() {
		super.onInit();
		tv_title = (TextView) findViewById(R.id.tv_title);
		View ll_head = getLayoutInflater().inflate(R.layout.head_class_comment,
				null);

		ImageView commentStatistics = (ImageView) findViewById(R.id.comment_statistics);
		commentStatistics.setOnClickListener(this);
		mPieChart = (PieChart) ll_head.findViewById(R.id.statistics_piechart);
		mList = (XListView) findViewById(R.id.list);
		tv_title.setText(currentChildName + "课堂评价");
		mList.addHeaderView(ll_head);

		mList.setPullLoadEnable(false);
		mList.setPullRefreshEnable(true);
		mList.setXListViewListener(this);
		adapter = new ClassRoomCommentStatisticsAdapter(mContext, listInfos);
		mList.setAdapter(adapter);

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		mSpUtil.setNotification(mSpUtil.getCurrentChildId() + "c",
				0);
		sendBroadcast(new Intent(BannerFragment.BANNER_COMMENT_CHANGED));
	}
	@Override
	protected void onData() {
		getStatisticsData(timeType);
		getStatisticsLists(timeType);

	}

	/**
	 * 获得统计列表
	 */
	private void getStatisticsLists(String string) {

		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("date", string);// 默认是0
		sendMap.put("page", page);
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.GET_STATISTICS_LIST, sendMap);
		MyAsyncHttp.get(mContext, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				mList.stopLoadMore();
				mList.stopRefresh();
				mList.setPullLoadEnable(false);
				if (resuleCode == RESULTCODE.SUCCESS) {
					ArrayList<StatisticsListInfo> temp = ResponseUtils
							.getStatisticsListInfos(mContext, result);
					if (temp != null) {
						if (page == 1) {
							if(temp.size()==0){
								showEmpty("没有与该学生相关的课堂评价");
								return;
							}else{
								hidEmpty();
							}
							listInfos = temp;
							if (adapter != null)
								adapter = null;
							adapter = new ClassRoomCommentStatisticsAdapter(
									mContext, listInfos);
							mList.setAdapter(adapter);
						} else {
							for (StatisticsListInfo statisticsListInfo : temp) {
								listInfos.add(statisticsListInfo);
							}
							adapter.notifyDataSetChanged();
						}

						if (temp.size() < 10) {
							mList.setPullLoadEnable(false);
						} else {
							page++;
							mList.setPullLoadEnable(true);
						}
						adapter.notifyDataSetChanged();
					}

				}

			}
		});
	}

	/**
	 * 获得统计的数据
	 * 
	 * @param string
	 */
	private void getStatisticsData(String string) {
		// showLoading();
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("date", string);// 默认是0
		String requestUrl = ParamsUtils.buildParams(NetWorkApi.GET_STATISTICS,
				sendMap);
		MyAsyncHttp.get(mContext, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				// hideLoading();
				if (resuleCode == RESULTCODE.SUCCESS) {
					Log.e("===", result);
					ArrayList<StatisticsInfo> infos = ResponseUtils
							.getStatisticsInfos(mContext, result);

					showChart(mPieChart, infos);
				}

			}

		});
	}

	private void showChart(PieChart pieChart,
			List<StatisticsInfo> statisticsList2) {

		PieData mPieData = getPieData(statisticsList2);
		pieChart.setHoleColorTransparent(true);
		pieChart.setHoleRadius(0); // 半径
		pieChart.setTransparentCircleRadius(0); // 半透明圈
		pieChart.setDescription("");
		pieChart.setDrawCenterText(false); // 饼状图中间可以添加文字
		pieChart.setDrawHoleEnabled(true);
		pieChart.setRotationAngle(90); // 初始旋转角度
		pieChart.setRotationEnabled(false); // 可以手动旋转
		pieChart.setUsePercentValues(true); // 显示成百分比
		pieChart.setNoDataTextDescription("There is no data");
		pieChart.setDrawSliceText(false);

		// 设置标注的信息
		Legend mLegend = pieChart.getLegend(); // 设置比例图
		mLegend.setPosition(LegendPosition.BELOW_CHART_LEFT); // 最右边显示
		mLegend.setTextColor(getResources().getColor(R.color.chart_title_color));
		mLegend.setXEntrySpace(7f);
		mLegend.setYEntrySpace(5f);
		// 设置比例块换行...
		mLegend.setWordWrapEnabled(true);
		mLegend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);

		pieChart.animateXY(1000, 1000); // 设置动画
		// 设置数据
		pieChart.setData(mPieData);
		pieChart.invalidate();

	}

	/**
	 * 
	 * @param count
	 *            分成几部分
	 * @param range
	 */

	private PieData getPieData(List<StatisticsInfo> statisticsList) {

		ArrayList<String> xValues = new ArrayList<String>(); // xVals用来表示每个饼块上的内容
		ArrayList<Entry> yValues = new ArrayList<Entry>(); // yVals用来表示封装每个饼块的实际数据

		for (int i = 0; i < statisticsList.size(); i++) {
			if (!"0".equals(statisticsList.get(i).count)) {
				xValues.add(statisticsList.get(i).title);
				yValues.add(new Entry(NumberFormatUtil
						.getFloatFromString(statisticsList.get(i).count), i));
			}
		}

		// y轴的集合
		PieDataSet pieDataSet = new PieDataSet(yValues, "");// "Quarterly Revenue 2014"/*显示在比例图上*/);
		if (yValues.size() > 1) {
			pieDataSet.setSliceSpace(5f); // 设置个饼状图之间的距离

		} else {
			pieDataSet.setSliceSpace(0f);
		}

		ArrayList<Integer> colors = new ArrayList<Integer>();

		// 饼图颜色
		colors.add(Color.rgb(253, 96, 96));
		colors.add(Color.rgb(155, 220, 120));
		colors.add(Color.rgb(155, 122, 255));
		colors.add(Color.rgb(119, 220, 204));
		colors.add(Color.rgb(122, 158, 254));
		colors.add(Color.rgb(101, 118, 163));
		colors.add(Color.rgb(203, 204, 205));
		colors.add(Color.rgb(90, 114, 100));
		if (yValues.size() > 8) {
			int r = 0;
			int g = 0;
			int b = 0;
			for (int i = 5; i < yValues.size(); i++) {
				r = (int) (Math.random() * 255 + 1);
				g = (int) (Math.random() * 255 + 1);
				b = (int) (Math.random() * 255 + 1);
				colors.add(Color.rgb(r, g, b));
			}
		}
		pieDataSet.setColors(colors);

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		float px = 5 * (metrics.densityDpi / 160f);
		pieDataSet.setSelectionShift(px); // 选中态多出的长度

		PieData pieData = new PieData(xValues, pieDataSet);

		pieData.setValueFormatter(new PercentFormatter());
		pieData.setValueTextSize(10f);
		pieData.setValueTextColor(getResources().getColor(R.color.white));

		return pieData;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.comment_statistics:
			if (mywindow == null) {
				mywindow = new ClubWindow(this, this);
			}
			mywindow.showPopupWindow(v);
			break;
		case R.id.tv_title:
			showChildrenWindow(v);
			break;
		default:
			break;
		}
	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	public void onClickClubWindowListener(int time, String typeName) {
		page = 1;
		this.timeType = typeName;
		getStatisticsData(typeName);
		getStatisticsLists(typeName);
	}

	@Override
	public void onRefresh() {
		page = 1;
		listInfos.clear();
		getStatisticsData(timeType);
		getStatisticsLists(timeType);

	}

	@Override
	public void onLoadMore() {
		getStatisticsLists(timeType);
	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		selectChildId = myChild.child_id;
		tv_title.setText(currentChildName + "课堂评价");
		getStatisticsData(timeType);
		getStatisticsLists(timeType);
	}

}
